<template>
  <!-- recommend vue prop sort
  is v-for v-if v-else-if v-else v-show v-cloak v-pre v-once id ref key slot v-model all-normal-props v-bind v-on v-html v-text-->
  <div>
    <div class="form-wrap">
      <div class="info-field">
        <span class="label">身份证号:</span>
        <input
          v-model="form.idCard"
          class="input-block"
          type="text"
          placeholder="填写身份证号"
          placeholder-class="placeholder-part"
          @confirm="getMerIdList"
        >
      </div>
      <div class="info-field">
        <span class="label">选择商户:</span>
        <picker
          v-model="pickerVal"
          class="input-block input-picker"
          :range="list"
          range-key="label"
          @change="handleMerIdChange"
        >
          <span
            class="picker-value"
            :class="{placeholder:!pickerVal}"
          >{{selectedMerName}}</span>
          <img
            src="https://akk.028wkf.cn/kdb-weapp-img/icon/xzlm.png"
            mode="aspectFill"
            class="select-icon"
          >
        </picker>
      </div>
      <p class="tip" @click="handleGenerateNewMerId">没有商户？立即开通</p>
      <button
        class="btn-round-blue"
        :disabled="disabled"
        @click="handleBind"
      >绑定该商户</button>
    </div>

    <web-view v-if="openURL" :src="openURL"></web-view>
  </div>
</template>

<script>
import {} from '@/utils'
import { FIND_MER_ID_BY_ID_CARD, OPEN_PAYMENT, GENERATE_NEW_MER } from '@/api'

export default {
  components: {},
  props: {},
  data () {
    return {
      form: { payMerId: null, state: null },
      merList: [],
      pickerVal: null,
      openURL: ''
    }
  },
  computed: {
    disabled () {
      return !this.form.payMerId
    },
    list () {
      return this.merList.map(_ => ({
        label: _.merName,
        value: _.tlMerId,
        state: _.merStatus
      }))
    },
    selectedMerName () {
      if (this.pickerVal) {
        return this.list[this.pickerVal].label
      } else {
        return '选择要绑定的商户'
      }
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    this.openURL = ''
  },
  methods: {
    handleBind () {
      if (!this.form.payMerId) {
        this.$toast('请选择一个商户')
      } else {
        this.bindMer()
      }
    },
    handleMerIdChange (e) {
      let val = e.target.value
      this.pickerVal = val
      this.form.payMerId = this.list[val].value
      this.form.state = this.list[val].state
    },
    handleGenerateNewMerId () {
      if (!this.form.idCard) {
        this.$toast('请输入身份证号')
      } else {
        this.createMer()
      }
    },

    getMerIdList () {
      const vm = this

      if (!vm.form.idCard) {
        return false
      }

      FIND_MER_ID_BY_ID_CARD(vm.form.idCard)
        .then(r => {
          if (r.data.code === '0') {
            vm.merList = r.data.data
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    bindMer () {
      const vm = this

      let params = {
        shopId: vm.$store.state.account.shopId,
        ...vm.form
      }

      OPEN_PAYMENT(params)
        .then(r => {
          if (r.data.code === '0' && r.data.data) {
            vm.$toast('操作成功')
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    createMer () {
      const vm = this

      let params = {
        token: vm.form.idCard,
        providerId: vm.$store.state.account.providerId,
        isShop: 'Y'
      }

      GENERATE_NEW_MER(params)
        .then(r => {
          if (r.data.code === '0') {
            let { merId } = r.data.data
            // let { url } = r.data.data
            // let reg = /:/g
            // vm.openURL = url.replace(reg, 's' + ':')
            // vm.openURL = url
            console.log(merId)
            wx.navigateToMiniProgram({
              appId: 'wxc5eef9244e1d68a8',
              path: 'pages/apply/main?merId=' + merId + '&isNav=true',
              // extraData: {
              //   foo: 'bar'
              // },
              // develop（开发版），trial（体验版），release（正式版）
              envVersion: 'release',
              success (res) {
                // 打开成功
                console.log(res)
              }
            })
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';

.form-wrap {
  > .info-field {
    > .input-picker {
      height: 28.25px;
      line-height: 28.25px;
      position: relative;
      .picker-value {
        font-size: 15px;
        &.placeholder {
          color: $gray;
        }
      }
      .select-icon {
        position: absolute;
        width: 8px;
        height: 16px;
        top: 50%;
        right: 15px;
        transform: translateY(-50%) rotate(90deg);
      }
    }
  }
  > .tip {
    color: $blue;
    font-size: 12px;
    margin-top: 30px;
  }
  > .btn-round-blue {
    margin-top: 50px;
  }
}
</style>
